import { BarChart } from 'echarts/charts'
import echarts, { createVNode, legend, tooltip, colorPicker } from './utils.jsx'
import merge from 'lodash/merge'
import { log } from '@/utils/logger'
import debounce from 'lodash.debounce'

echarts.use(BarChart)

const defaultOptions = {
  color: colorPicker,
  legend,
  tooltip,
  grid: {
    top: 30,
    right: 10,
    bottom: 20
  }
}

export default {
  name: 'ProBarChart',
  props: {
    options: Object,
    lazy: Boolean,
    resize: Boolean,
    refreshKey: [String, Number, Symbol, Boolean]
  },
  data() {
    return {
      instance: null
    }
  },
  watch: {
    refreshKey() {
      this.render()
    }
  },
  mounted() {
    if (!this.lazy) {
      this.render()
    }
  },
  beforeDestroy() {
    if (this.instance && !this.instance.isDisposed) {
      this.instance.dispose()
    }
    this.instance = null
  },
  methods: {
    setOptions(options) {
      const finalOptions = merge(defaultOptions, options)
      log('bar-chart\'s option is: ', finalOptions)
      return finalOptions
    },
    render() {
      const dom = this.$refs.host
      const options = this.setOptions(this.options)

      if (!dom || !this.options) return
      if (!this.instance) {
        this.instance = echarts.init(dom)
      }

      this.instance.setOption(options)
    },
    _resizeHandler({ width, height }) {
      if (this.resize) {
        this.instance.resize()
      }
      this.$emit('resize', width, height)
    }
  },
  render(createElement) {
    const host = createVNode({
      h: createElement,
      className: 'is-bar',
      useResize: this.resize,
      resizeFn: debounce(this._resizeHandler, 300)
    })
    return host
  }
}
